package stud.aistar.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.File;
import java.util.UUID;

public class QiniuCloudUtil {

    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "Yq_5ZHf2i3txAo32d_R5OtN0jOoalDUahrgChjA_";//ACCESS_KEY
    private static final String SECRET_KEY = "ULaCNDK4gN885vYk4p2vl7j1qOisbToidFS5Z79Q";//SECRET_KEY

    // 要上传的空间
    private static final String bucketname = "jybddd";//七牛云存储空间名

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static final String DOMAIN = "http://q01chxhrv.bkt.clouddn.com/";//你的图片上传路径

//    private static final String style = "imagestyle";

    private static UploadManager uploadManager = new UploadManager(); // 创建上传对象


    //设置新文件的文件名
    private static String newName(String oldName) {
        String[] datas = oldName.split("\\.");
        String type = datas[datas.length - 1];
        String newName = UUID.randomUUID().toString() + "." + type;
        return newName;
    }

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了 //
    private static String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public static String upload(byte[] bytes,String fileName){
        String url = null;
        Response res = null;
        String imgName = null;
        String key = newName(fileName);//七牛云服务器里用来对应唯一上传的文件
        try {
            res = uploadManager.put(bytes, key, getUpToken());
            imgName = (String) res.jsonToMap().get("key");
            url = DOMAIN+imgName;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return url;

    }
    public static String upload(File file,String fileName){
        String url = null;
        Response res = null;
        String imgName = null;
        try {
            res = uploadManager.put(file, newName(fileName), getUpToken());
            imgName = (String) res.jsonToMap().get("key");
            url = DOMAIN+imgName;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return url;
    }
}